<template>
  <div class="app-container">
    <el-form ref="listFilterRef" :model="list.filter" inline>
      <el-form-item prop="name">
        <el-input
          v-model="list.filter.name"
          clearable
          placeholder="商品名称 / 商品编码"
        />
      </el-form-item>
      <!-- 企业只有一个商户，不需要商户筛选 -->
      <el-form-item prop="mchId" v-if="isPlatFormUser">
        <merchant-select
          v-model="list.filter.mchId"
          search-key="mchId"
          placeholder="商户"
        />
      </el-form-item>
      <el-form-item prop="subMchId">
        <SubMchSelect
          v-model="list.filter.subMchId"
          search-key="subMchId"
          placeholder="商铺"
        />
      </el-form-item>
      <el-form-item prop="status">
        <KiSelect
          v-model="list.filter.status"
          :options="options.statusArray"
          placeholder="商品状态"
          :props="{ value: 'value', label: 'label' }"
        />
      </el-form-item>
      <el-form-item prop="categoryIds">
        <CategorySelect
          v-model="list.filter.categoryIds"
          placeholder="商品分类"
          clearable
          multiple
          :status="2"
          :parent-id="state.businessTypeId"
          :max-level="2"
          :check-strictly="true"
          :collapse-tags="false"
          class="category-select"
          canSelectDisabledItem
          :props="{ multiple: true }"
        />
      </el-form-item>
      <el-form-item prop="mchAreaCodes">
        <AllRegionSelect
          v-model="list.filter.mchAreaCodes"
          placeholder="商户所在地区"
          :props="{ multiple:true }"
        />
      </el-form-item>
      <el-form-item prop="beginTime">
        <el-date-picker
          style="width: 202px"
          v-model="list.filter.beginTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="商品创建开始时间"
        />
      </el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          style="width: 202px"
          v-model="list.filter.endTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="商品创建结束时间"
        />
      </el-form-item>
      <el-button @click="reset">重置</el-button>
    </el-form>

    <div flex="~" justify="between" m="y-10px">
      <span class="table-operation">
        <el-button
          v-if="hasBtn['新增']"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="c"
        >
          新增
        </el-button>
        <ExportExcel
          v-if="hasBtn['导出']"
          :url="
            ENUMS.ENUM_URL_PREFIX[this.state.businessTypeId] +
            '/' +
            ENUMS.ENUM_AXIOS_CONFIG[this.state.businessTypeId].exportList.url
          "
          :param="{
            businessTypeId: this.state.businessTypeId,
            ...this.list.filter
          }"
        />
      </span>
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
      />
    </div>

    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column label="商品ID" prop="id"/>
      <el-table-column label="商品品类" prop="categoryName"/>
      <el-table-column label="商品名称" prop="name"/>
      <el-table-column label="商品售价(元)">
        <template slot-scope="scope">
          <div>￥ {{ scope.row.currentPrice | $cent2yuan }}</div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="isPlatFormUser"
        label="商户名称"
        prop="merchantName"
      />
      <el-table-column label="店铺名称" prop="subMchName"/>
      <el-table-column label="创建时间" prop="createTime"/>
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row: { id, status } }">
          <KiPopSwitch
            v-bind="popSwitchProps(status)"
            @change="updateStatus({ id, status: status ^ 1 })"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作栏" :min-width="121" align="center">
        <template slot-scope="scope">
          <KiPopButton
            v-if="hasBtn['查看']"
            @click="r({
              id: scope.row.id,
              businessTypeId: state.businessTypeId,
              // 平台用户 / 外部引用不传 mchId
              ...!isPlatFormUser && { mchId: userInfo.merchantId },
            })"
          >
            查看
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['编辑']"
            @click="u({
              id: scope.row.id,
              businessTypeId: state.businessTypeId,
              // 平台用户 / 外部引用不传 mchId
              ...!isPlatFormUser && { mchId: userInfo.merchantId },
            })"
          >
            编辑
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['复制新增']"
            @click="() => {
              // 复制新增本质上也是新增，没必要新增一种表单状态
              // 如果新增一种状态，那么需要判断表单状态的地方都要增加一种判断，容易漏
              // 复制新增和新增的区别就是表单标题不一样，以及需要查询详情
              // 表单标题用辅助变量去判断即可
              // 查询详情，在 openForm 中传参即可实现
              // 对于 openForm，传参即调用查询详情接口，不传参则不调用
              createFromCopy__ = true
              c({
                id: scope.row.id,
                businessTypeId: state.businessTypeId,
                // 平台用户 / 外部引用不传 mchId
                ...!isPlatFormUser && { mchId: userInfo.merchantId },
              })
            }"
          >
            复制新增
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['酒店日历']"
            @click="e => $bus.emit('hotel-calendar:open', scope.row.id)"
          >
            酒店日历
          </KiPopButton>
          <!-- 票务库存日历 -->
          <!-- 企业账号具有查看/编辑权限，平台账号具有查看权限 -->
          <KiPopButton
            v-if="hasBtn['库存日历']"
            @click="
              e => {
                isPlatFormUser
                  ? $bus.emit('ticket-stock-calendar:detail', scope.row.id)
                  : $bus.emit('ticket-stock-calendar:update', scope.row.id)
              }
            "
          >
            库存日历
          </KiPopButton>
          <!-- 票务限购设置 -->
          <!-- 企业账号具有查看/编辑权限，平台账号具有查看权限 -->
          <KiPopButton
            v-if="hasBtn['限购设置']"
            @click="
              e => {
                isPlatFormUser
                  ? $bus.emit('ticket-purchase-limit:detail', scope.row.id)
                  : $bus.emit('ticket-purchase-limit:update', scope.row.id)
              }
            "
          >
            限购设置
          </KiPopButton>
          <!-- 票务退票设置 -->
          <!-- 企业账号具有查看/编辑权限，平台账号具有查看权限 -->
          <KiPopButton
            v-if="hasBtn['退款设置']"
            @click="
              e => {
                isPlatFormUser
                  ? $bus.emit('ticket-refund:detail', scope.row.id)
                  : $bus.emit('ticket-refund:update', scope.row.id)
              }
            "
          >
            退款设置
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['授权商户管理']"
            @click="
              e =>
                $bus.emit(
                  'auth-merchant-manager:open',
                  scope.row.mchId,
                  scope.row.id
                )
            "
          >
            授权商户管理
          </KiPopButton>
          <!-- 授权云仓市场 -->
          <!-- 企业账号具有查看/编辑权限，平台账号具有查看权限 -->
          <KiPopButton
            v-if="hasBtn['授权云仓市场']"
            @click="
              e => {
                isPlatFormUser
                  ? $bus.emit('auth-cloud-market:detail', {
                      mchId: scope.row.mchId,
                      productId: scope.row.id,
                      row: scope.row
                    }) // 平台用户
                  : $bus.emit('auth-cloud-market:update', {
                      mchId: scope.row.mchId,
                      productId: scope.row.id,
                      row: scope.row
                    }) // 企业用户
              }
            "
          >
            授权云仓市场
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['同步最新库存']"
            @click="resetForbiddenStatus(scope.row.id)"
          >
            同步最新库存
          </KiPopButton>
          <KiPopButton
            v-if="hasBtn['删除']" text="![#FF7575]"
            :elPopconfirmProps="{ title: '确认删除吗？' }"
            @click="
              d({
                id: scope.row.id,
                businessTypeId: state.businessTypeId
              })
            "
          >
            删除
          </KiPopButton>
        </template>
      </el-table-column>
    </el-table>

    <Form
      ref="formRef"
      :form.sync="form"
      :formTitle="formTitle"
      :submitForm="submitForm"
      @closed="() => {
        createFromCopy__ = false
      }"
    />

    <!-- 酒店日历房间状态组件 -->
    <HotelCalendar/>
    <!-- 票务退购组件 -->
    <TicketRefund/>
    <!-- 票务限购组件 -->
    <TicketPurchaseLimit/>
    <!-- 票务日历库存组件 -->
    <TicketStockCalendar/>
    <!-- 授权云仓市场组件 -->
    <AuthCloudMarket/>
  </div>
</template>

<script>
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import pageMixin from '@/utils/pageMixin'
import { state, mutations } from '../store'
import ENUMS from '../enums'
import { mapGetters } from 'vuex'
import merchantSelect from '@/components/merchantSelect'
import SubMchSelect from '@/components/SubMchSelect'
import HotelCalendar from './dialogs/HotelCalendar.vue'
import TicketRefund from './dialogs/TicketRefund.vue'
import AuthCloudMarket from './dialogs/AuthCloudMarket.vue'
import TicketPurchaseLimit from './dialogs/TicketPurchaseLimit.vue'
import TicketStockCalendar from './dialogs/TicketStockCalendar/index.vue'
import CategorySelect from '@/components/CategorySelect/index.vue'
import Form from '../form'
import VueBus from 'vue-bus'
import Vue from 'vue'

Vue.use(VueBus)

export default {
  components: {
    Form,
    merchantSelect,
    TicketRefund,
    HotelCalendar,
    AuthCloudMarket,
    TicketPurchaseLimit,
    TicketStockCalendar,
    CategorySelect,
    SubMchSelect,
  },
  mixins: [pageMixin],
  props: {
    businessTypeId: {
      type: String,
      required: true
    }
  },
  setup: props => {
    mutations.updateBusinessTypeId(props.businessTypeId)

    const {
      list,
      form,
      getList,
      c,
      r,
      u,
      d,
      updateStatus,
      submitForm,
      formTitle,
      reset,
      listFilterRef
    } = useAdmateAdapter({
      urlPrefix: ENUMS.ENUM_URL_PREFIX[state.businessTypeId],
      axiosConfig: ENUMS.ENUM_AXIOS_CONFIG[state.businessTypeId],
      list: {
        filter: {
          businessTypeId: state.businessTypeId,
          orderBy: ' a.update_time  desc ',
          mchAreaCodes: [],
          categoryIds: []
        }
      },
      form: {
        data: ENUMS.ENUM_DEFAULT_FORM_DATA[state.businessTypeId],
      },
      submitFormProxy (submitForm) {
        return new Promise((resolve, reject) => {
          submitForm().then(res => {
            resolve()
          }).catch(() => {
            reject()
          })
        })
      },
    }, {
      getElFormRefOfFormData() {
        return this.$refs.formRef
      },
    })

    return {
      list,
      form,
      getList,
      c,
      r,
      u,
      d,
      updateStatus,
      submitForm,
      formTitle,
      reset,
      listFilterRef
    }
  },
  data () {
    return {
      state,
      createFromCopy__: false,
      ENUMS,
    }
  },
  computed: {
    ...mapGetters(['isPlatFormUser', 'isBelongAgencyId', 'isAdmin', 'userInfo']),
    paneNumCmp () {
      return val => (val ? '(' + val + ')' : '')
    }
  },
  created () {
    this.$bus.on('global:list:refresh', this.getList)
  },
  beforeDestroy () {
    this.$bus.off('global:list:refresh', this.getList)
  },
  methods: {
    resetForbiddenStatus (id) {
      const loading = this.$loading()
      this.$POST(ENUMS.ENUM_URL_PREFIX['1'] + '/resetForbiddenStatus', { id })
      .then(() => {
        this.$swal.success('同步成功')
      })
      .finally(() => {
        loading.close()
      })
    },
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-tabs .el-tabs__header) {
  font-weight: bold;
  margin-bottom: 0;
  border-bottom: none;

  .el-tabs__item {
    font-weight: bold;
    font-size: 16px;
    border-bottom: none;

    &.is-active {
      color: #ffffff;
      background-color: #fe9800;
    }
  }
}
</style>
